package com.backapp.app;

import java.io.*;
import java.util.*;

import com.dropbox.client2.*;
import com.dropbox.client2.DropboxAPI.Entry;
import com.dropbox.client2.android.*;

import android.os.*;

public class DownloadFiles extends AsyncTask<List<Entry>, Void, List<String>>
{
	private DropboxAPI<AndroidAuthSession> mDBApi;
	private DBDownloadListener mListener;
	
	public
	DownloadFiles(
		DropboxAPI<AndroidAuthSession> dBApi,
		DBDownloadListener listener
		)
	{
		mDBApi = dBApi;
		mListener = listener;
	}
	
	@Override
	protected List<String> 
	doInBackground(
		List<Entry>... params
		)
	{
		List<String> filesDownloaded = null;
		String appName;
		
		try
		{
			makeTempDir("backapp");
		
			filesDownloaded = new ArrayList<String>();
			
			for (Entry entry : params[0])
			{
				Utils.logInfo("To download: " + entry.fileName());
				appName = entry.fileName().split("\\.")[0];
				makeTempDir("backapp/" + appName);
				filesDownloaded.add(createFile(entry, appName));
			}
		}
		catch (Exception e)
		{
			//
			// TODO error handling
			//
			
			Utils.logError(e.getMessage());
			return null;
		}
		
		return filesDownloaded;
	}
	
	private void
	makeTempDir(
			String name
			)
	throws Exception
	{
		File targetDir = null;
		boolean targetDirCreated;
		
    	try
    	{
    		targetDir = new File(Utils.SDCARD.getCanonicalPath() + "/tmp/" + name);
    		
    		if (!targetDir.exists())
    		{
    			targetDirCreated = targetDir.mkdir();
        		
        		if (!targetDirCreated)
        		{
        			throw new Exception("backup directory could not be created.");
        		}
    		}
    	}
    	catch (IOException e)
    	{
    		throw new Exception("Could not open file: " + e.getMessage());
    	}
	}
	
	private String
	createFile(
		Entry entry,
		String appName
		)
		throws Exception
	{
		File newFile = null;
		FileOutputStream outputStream = null;
		
		try
		{
			newFile = new File(
				Utils.SDCARD.getCanonicalPath() + "/tmp/backapp/" + 
				appName + "/" + entry.fileName().replace(appName + ".", ""));
			
			Utils.logInfo("Creating file: " + newFile.getAbsolutePath());
			
			outputStream = new FileOutputStream(newFile);
		
			mDBApi.getFile(entry.path, null, outputStream, null);
		} 
		catch (IOException e)
		{
			throw new Exception("Could not open file: " + e.getMessage());
		}
		finally 
		{
		    if (outputStream != null) 
		    {
		        try 
		        {
		            outputStream.close();
		        } 
		        catch (IOException e) 
		        {
	        	}
	        }
	    }
		
		return newFile.getAbsolutePath();
	}
	
	@Override
	protected void 
	onPostExecute(
		List<String> result
		)
	{
		super.onPostExecute(result);
		Utils.logInfo("DownLoadFiles: postExecute");
		mListener.onDBDownLoadCompleted(result);
	}
}
